package com.utils;

import org.apache.tomcat.jni.Local;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * @author ben.huang
 */
@Component
public class MessageUtil {
    private static MessageSource messageSource;

    private String baseName = "classpath:static/i18n/messages";

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageResource(){
        ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
        source.setBasename(baseName);
        source.setDefaultEncoding("UTF-8");
        source.setUseCodeAsDefaultMessage(true);
        messageSource = source;
        return source;

    }

    /**
     *  获取单个翻译项，出错则返回原来的参数
     * @param msgKey
     * @return
     */
    public static String get(String msgKey){
        try {
            return messageSource.getMessage(msgKey,null, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            return msgKey;
        }
    }

    /**
     *
     * @param msgKey
     * @param args
     * @return
     */
    public static String get(String msgKey,Object[] args){
        try {
            return messageSource.getMessage(msgKey,args,LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            return msgKey;
        }
    }

    /**
     *  按照指定语言查询翻译项
     * @param msgKey
     * @param locale
     * @return
     */
    public static String get(String msgKey, Locale locale){
        try {
            return messageSource.getMessage(msgKey,null,locale);
        } catch (NoSuchMessageException e) {
            return msgKey;
        }
    }
}
